import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpService } from '../../../service/http.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
})
export class UserComponent {
  public pageInfo: any = {
    pageSize: 10,
    pageNum: 1,
    total: 0,
  };
  public dataList: any = [];
  public showAddFlag = false;
  public showUpdateFlag = false;
  public AddUserInfo: any = {
    id: 0,
    name: '',
    password: '',
    confirmPassword: '',
    email: '',
  };

  constructor(
    private router: Router,
    private httpService: HttpService,
    private modalService: NzMessageService,
  ) {}

  ngOnInit() {
    this.getList();
  }

  getList() {
    const url =
      '/rest/user/pageNum/' +
      this.pageInfo.pageNum +
      '/pageSize/' +
      this.pageInfo.pageSize;
    const data = {};
    return this.httpService.post(url, data).subscribe((res: any) => {
      this.dataList = [];
      this.pageInfo.pageSize = res.page.pageSize;
      this.pageInfo.pageNum = res.page.pageNum;
      this.pageInfo.total = res.page.total;
      this.dataList = res.data;
    });
  }

  showAdd() {
    this.AddUserInfo.name = '';
    this.AddUserInfo.password = '';
    this.AddUserInfo.confirmPassword = '';
    this.AddUserInfo.email = '';
    this.showAddFlag = true;
  }

  handleCancel() {
    this.showAddFlag = false;
  }

  deleteConfirm(id: any) {
    const url = '/rest/user/' + id;
    return this.httpService.delete(url).subscribe((res: any) => {
      this.getList();
    });
  }

  cancel() {
    this.showAddFlag = false;
  }

  addUser() {
    const url = '/rest/user';
    if (this.AddUserInfo.name == null || this.AddUserInfo.name == '') {
      this.modalService.error('用户名不能为空！');
      return;
    }
    if (this.AddUserInfo.password == null || this.AddUserInfo.password == '') {
      this.modalService.error('密码不能为空！');
      return;
    }
    if (this.AddUserInfo.password != this.AddUserInfo.confirmPassword) {
      this.modalService.error('两次密码输入不一致！');
      return;
    }
    const data = {
      email: this.AddUserInfo.email,
      password: this.AddUserInfo.password,
      name: this.AddUserInfo.name,
    };
    return this.httpService.post(url, data).subscribe((res: any) => {
      if (res.code == '0000') {
        this.modalService.success('添加成功！');
        this.showAddFlag = false;
        this.getList();
      } else {
        this.modalService.success(res.message);
      }
    });
  }

  update() {}
}
